package com.haitaoit.chengquan.module.home.activity.fabu;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Base64;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.view.WindowManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeOption;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.google.gson.Gson;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.IBaseActivity;
import com.haitaoit.chengquan.base.MyCallBack;
import com.haitaoit.chengquan.business.request.PublicServiceReqSeconde;
import com.haitaoit.chengquan.module.center.model.UserInfoModel;
import com.haitaoit.chengquan.module.home.adapter.forum.ImageAdapter;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.ui.equipment.request.ApiRequest;
import com.haitaoit.chengquan.ui.equipment.response.ResponseItem;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetAbserlutePath;
import com.haitaoit.chengquan.utils.GetPhotoListener;
import com.haitaoit.chengquan.utils.GetPhotoOrImage;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PhonUnmber;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.haitaoit.chengquan.utils.ZoomBitmap;
import com.haitaoit.chengquan.view.Img;
import com.haitaoit.chengquan.view.MyGridView;
import com.lidroid.xutils.ViewUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.nostra13.universalimageloader.core.ImageLoader;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by 赵航 on 2017/10/26.
 */

public class SecondHandServiceActivity extends IBaseActivity {
    @ViewInject(R.id.title_img)
    ImageView  title_img;//头图片
    @ViewInject(R.id.service_type_tv)
    TextView   service_type_tv;//第一行文字
    @ViewInject(R.id.service_title)
    EditText   service_title;//服务标题
    @ViewInject(R.id.service_desc)
    EditText   service_desc;//详细描述
    @ViewInject(R.id.service_lowprice)
    EditText   service_lowprice;//最低价
    @ViewInject(R.id.service_highprice)
    EditText   service_highprice;//最高价
    @ViewInject(R.id.chenege_contment)
    EditText   chenege_contment;//机床型号
    @ViewInject(R.id.machine_id)
    EditText   machine_id;//系统类型
    @ViewInject(R.id.sistem_id)
    EditText   sistem_id;//机床品牌
    @ViewInject(R.id.machin_data)
    EditText   machin_data;//机床生产日期
    @ViewInject(R.id.machin_paizi)
    EditText   machin_paizi;//机床数量
    @ViewInject(R.id.name)
    EditText   name;//联系人
    @ViewInject(R.id.position)
    EditText   position;//职位
    @ViewInject(R.id.phone_number)
    EditText   phone_number;//电话号码
    @ViewInject(R.id.company_name)
    EditText   company_name;//公司名称
    @ViewInject(R.id.addrees_name)
    EditText   addrees_name;//公司地址
    @ViewInject(R.id.img_list)
    MyGridView img_list;//图片加载器
    @ViewInject(R.id.tv_fabu)
    TextView   tv_fabu;//发布
    private ImageAdapter adapter;
    // 上传的bitmap
    private Bitmap       upbitmap;
    private String file = "";
    private GetPhotoOrImage getPhotoOrImage;
    private int change = 0;


    private double latitude = 0;// 维度
    private double longitude = 0;// 经度
    private GeoCoder mSearch;
    private String mAccount_type;
    // 处理调用相机或者相册的图片回调
    private GetPhotoListener getPhoto1 = new GetPhotoListener() {
        @Override
        public void completeGetImage(String file, Bitmap upbitmap) {
            Img img = new Img();
            img.setBmp(upbitmap);
            img.setImg(file);
            List<Img> imgs = adapter.getList();
            imgs.add(img);
            adapter.setList(imgs);
            adapter.notifyDataSetChanged();
        }
    };

    // 处理调用相机或者相册的图片回调
    private GetPhotoListener getPhoto = new GetPhotoListener() {
        @Override
        public void completeGetImage(String file, Bitmap upbitmap) {
            Img img = new Img();
            img.setBmp(upbitmap);
            img.setImg(file);
            List<Img> imgs = adapter.getList();
            imgs.set(change, img);
            adapter.setList(imgs);
            adapter.notifyDataSetChanged();
        }
    };
    private BackCall         backCall = new BackCall() {
        @Override
        public void deal(int which, Object... obj) {
            int position = (Integer) obj[0];
            switch (which) {
                case R.id.icon:
                    if (position == adapter.getList().size()) {
                        getPhotoOrImage.setGetPhotoListener(getPhoto1);
                        getPhotoOrImage.getImage();
                    } else {
                        Dialog dlg = DialogUtil.ShowTop(mContext, new BackCall() {
                            @Override
                            public void deal(int which, Object... obj) {
                                switch (which) {
                                    case R.id.tv_photos:// 图库
                                        getPhotoOrImage.setGetPhotoListener(getPhoto);
                                        getPhotoOrImage.getImage();
                                        break;
                                    case R.id.tv_camera:
                                        List<Img> list = adapter.getList();
                                        list.remove(change);
                                        adapter.setList(list);
                                        adapter.notifyDataSetChanged();
                                        break;
                                }
                                super.deal(which, obj);
                            }
                        });
                        dlg.setCanceledOnTouchOutside(true);
                        dlg.show();

                        DisplayMetrics metric = new DisplayMetrics();
                        mContext.getWindowManager().getDefaultDisplay().getMetrics(metric);
                        int width = metric.widthPixels; // 屏幕宽度（像素）
                        WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                        params.width = width;
                        params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                        dlg.getWindow().setAttributes(params);
                    }
                    break;
            }
            super.deal(which, obj);
        }
    };


    private OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
        public void onGetGeoCodeResult(GeoCodeResult result) {
            if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {//获取地址
                // 没有检索到结果
                ToastUtils.showToast("亲,您的地址是无效的,请重新填写哦!");
                tv_fabu.setEnabled(true);
            } else {// 获取地理编码结果
                Log.e("tag", "result1:" + result.getAddress() + "====" + result.getLocation().latitude + "-----" + result.getLocation().longitude);
                latitude = result.getLocation().latitude;
                longitude = result.getLocation().longitude;
                // 发布
                publiceToAll();
            }
        }

        @Override
        public void onGetReverseGeoCodeResult(ReverseGeoCodeResult reverseGeoCodeResult) {
            if (reverseGeoCodeResult == null || reverseGeoCodeResult.error != SearchResult.ERRORNO.NO_ERROR) {
                //没有找到检索结果
            } else {// 获取反向地理编码结果
                Log.e("tag", "reverseGeoCodeResult1:" + reverseGeoCodeResult.toString());
            }

        }
    };

    @Override
    protected int setContentView() {
        return R.layout.secondhandserviceactivity_send_service;
    }

    @Override
    protected String setTitle() {
        return "二手设备买卖 发布服务";
    }

    @Override
    protected void initView() {
        ViewUtils.inject(this);

        adapter = new ImageAdapter(this);
        adapter.setBackCall(backCall);
        img_list.setAdapter(adapter);
        getPhotoOrImage = new GetPhotoOrImage(this);

        title_img.setOnClickListener(this);
        tv_fabu.setOnClickListener(this);

        String address = PreferenceUtils.getPrefString("address", "");
        addrees_name.setText(address);
        //获取个人信息并对所需要填的信息进行返回
        httpGetUserInfo(Constant.Getgr_user_model);


    }

    private void httpGetUserInfo(String url) {
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("user_id", PreferenceUtils.getPrefString("user_id", ""));
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(SecondHandServiceActivity.this, false, url, params, new RequestCallBack<String>() {
            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsonString = arg0.result.toString();
                JSONObject json;
                try {
                    json = new JSONObject(jsonString);
                    String Errcode = json.getString("ErrCode");
                    String Errmsg = json.getString("ErrMsg");
                    String Response = json.getString("Response");
                    Gson gson = new Gson();
                    switch (Integer.valueOf(Errcode)) {
                        case 1:// 失败

                            return;
                        case 0:// 成功
                            UserInfoModel user_info = gson.fromJson(Response, UserInfoModel.class);
                            name.setText(user_info.getNet_name());
                            phone_number.setText(user_info.getPhone());
                            return;
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("获取数据失败,请检查网络");
            }
        });
    }
    @Override
    protected void initData() {

    }

    @Override
    protected void viewOnClick(View v) {
        switch (v.getId()) {
            //调用头图片
            case R.id.title_img:
                Dialog dlg = DialogUtil.ShowPhotoDialog(this, new BackCall() {
                    @Override
                    public void deal(int which, Object... obj) {
                        switch (which) {
                            case R.id.tv_photos:// 图库
                                Intent intent = new Intent();
                                intent.setAction(Intent.ACTION_GET_CONTENT);
                                intent.addCategory(Intent.CATEGORY_OPENABLE);
                                intent.setType("image/*");
                                intent.putExtra("aspectX", 1);
                                intent.putExtra("aspectY", 1);
                                intent.putExtra("outputX", 500);
                                intent.putExtra("outputY", 500);
                                intent.putExtra("crop", "true");
                                intent.putExtra("return-data", true);
                                startActivityForResult(intent, 2);
                                break;
                            case R.id.tv_camera:
                                Intent in = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                startActivityForResult(in, 2);
                                break;
                        }
                        super.deal(which, obj);
                    }
                });
                dlg.setCanceledOnTouchOutside(true);
                dlg.show();

                DisplayMetrics metric = new DisplayMetrics();
                this.getWindowManager().getDefaultDisplay().getMetrics(metric);
                int width = metric.widthPixels; // 屏幕宽度（像素）
                WindowManager.LayoutParams params = dlg.getWindow().getAttributes();
                params.width = width;
                params.gravity = Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL;
                dlg.getWindow().setAttributes(params);
                break;
            case R.id.tv_fabu:
                tv_fabu.setEnabled(false);
                if (TextUtils.isEmpty(PreferenceUtils.getPrefString("user_id", ""))) {
                    Intent intent = new Intent(this, LoginActivity.class);
                    intent.putExtra("tag", "0");
                    startActivity(intent);
                    tv_fabu.setEnabled(true);

                } else if (!TextUtils.isEmpty(PreferenceUtils.getPrefString("user_id", "")) && !TextUtils.equals(PreferenceUtils.getPrefString("user_id", ""), "1")) {
                    if (TextUtils.isEmpty(service_title.getText().toString().trim())){
                        ToastUtils.showToast("请输入服务标题！");
                        tv_fabu.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(service_desc.getText().toString().trim())) {
                        ToastUtils.showToast("请输入详细描述！");
                        tv_fabu.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(service_lowprice.getText().toString().trim())) {
                        ToastUtils.showToast("请输入价格！");
                        tv_fabu.setEnabled(true);
                        return;
                    }  else if (TextUtils.isEmpty(chenege_contment.getText().toString().trim())) {
                        ToastUtils.showToast("请输入机床型号！");
                        tv_fabu.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(machine_id.getText().toString().trim())) {
                        ToastUtils.showToast("请输入系统型号！");
                        tv_fabu.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(sistem_id.getText().toString().trim())) {
                        ToastUtils.showToast("请输入机床品牌！");
                        tv_fabu.setEnabled(true);
                        return;
                    }else if (TextUtils.isEmpty(machin_data.getText().toString().trim())) {
                        ToastUtils.showToast("请输入机床生产日期！");
                        tv_fabu.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(machin_paizi.getText().toString().trim())) {
                        ToastUtils.showToast("请输入机床数量");
                        tv_fabu.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(name.getText().toString().trim())) {
                        ToastUtils.showToast("请输入联系人姓名！");
                        tv_fabu.setEnabled(true);
                        return;
                    }  else if (TextUtils.isEmpty(phone_number.getText().toString().trim())) {
                        ToastUtils.showToast("请输入联系人电话！");
                        tv_fabu.setEnabled(true);
                        return;
                    } else if (PhonUnmber.checkCellphone(phone_number.getText().toString().trim())) {
                        ToastUtils.showToast("联系人电话不正确");
                        tv_fabu.setEnabled(true);
                        return;
                    }else if (TextUtils.isEmpty(company_name.getText().toString().trim())) {
                        ToastUtils.showToast("请输入公司名称！");
                        tv_fabu.setEnabled(true);
                        return;
                    } else if (TextUtils.isEmpty(addrees_name.getText().toString().trim())) {
                        ToastUtils.showToast("请输入公司地址！");
                        tv_fabu.setEnabled(true);
                        return;
                    } else {
                        //                        开始发布
                        mSearch = GeoCoder.newInstance();
                        mSearch.geocode(new GeoCodeOption().city("").address(addrees_name.getText().toString()));
                        mSearch.setOnGetGeoCodeResultListener(listener);
                    }
                    break;
                }else {
                    tv_fabu.setEnabled(true);
                }
        }
    }

    //开始发布
    private void publiceToAll() {

        PublicServiceReqSeconde publicServiceReqSeconde = new PublicServiceReqSeconde();

        //标题图片
        PublicServiceReqSeconde.TitleImgBean titleImgBean = new PublicServiceReqSeconde.TitleImgBean();
        if (file == null || "".equals(file)) {
            file = bitmapToString(BitmapFactory.decodeResource(mContext.getResources(), R.mipmap.img20));
        }

        titleImgBean.setImg_url(file);
        //需求标题图片
        publicServiceReqSeconde.setTitle_img(titleImgBean);

        //轮播图片
        List<PublicServiceReqSeconde.ImgListBean> imgList = new ArrayList<PublicServiceReqSeconde.ImgListBean>();
        PublicServiceReqSeconde.ImgListBean imgBean;
        for (int i = 0; i < adapter.getList().size(); i++) {
            imgBean = new PublicServiceReqSeconde.ImgListBean();
            imgBean.setImg_url(adapter.getList().get(i).getImg());
            imgList.add(imgBean);
        }
        //需求轮播图
        publicServiceReqSeconde.setImg_list(imgList);


        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("user_id", PreferenceUtils.getPrefString("user_id", "")));
        String sign = GetSign.genPackageSign(list);

        //需求分类
        publicServiceReqSeconde.setType("6");//需求分类1设备维修2加工订单3机床耗材4机床配件5机床组立6二手设备买卖7二手设备改造
        //需求标题
        publicServiceReqSeconde.setTitle(service_title.getText().toString().trim());
        //详细描述
        publicServiceReqSeconde.setDescribe(service_desc.getText().toString().trim());
        //参考价格低
        publicServiceReqSeconde.setReference_price_low(service_lowprice.getText().toString().trim());
        //参考价格高
        publicServiceReqSeconde.setReference_price_high(service_highprice.getText().toString().trim());


        //机床型号
        publicServiceReqSeconde.setEshsbmm_machine(chenege_contment.getText().toString().trim());
        //系统型号
        publicServiceReqSeconde.setEshsbmm_system(machine_id.getText().toString().trim());
        //机床品牌
        publicServiceReqSeconde.setEshsbmm_machine_brands(sistem_id.getText().toString().trim());
        //机床生产日期
        publicServiceReqSeconde.setEshsbmm_machine_production_date(machin_data.getText().toString().trim());
        //机床数量
        publicServiceReqSeconde.setEshsbmm_machine_number(machin_paizi.getText().toString().trim());




        //联系人
        publicServiceReqSeconde.setContact(name.getText().toString().trim());
        //联系人职位
        publicServiceReqSeconde.setContact_position(position.getText().toString().trim());
        //联系人电话
//        publicServiceReqSeconde.setContact_phone(phone_number.getText().toString().trim());
        //公司名称
        publicServiceReqSeconde.setCompany_name(company_name.getText().toString().trim());
        //公司地址
        publicServiceReqSeconde.setCompany_address(addrees_name.getText().toString().trim());



        if (hasNetWork()) {
            ApiRequest.ServePubliceRequirement(PreferenceUtils.getPrefString("user_id", ""), sign, publicServiceReqSeconde, new MyCallBack<ResponseItem>(mContext) {
                @Override
                public void onSuccessful(ResponseItem response) {
                    tv_fabu.setEnabled(true);
                    if (response.getErrCode() == 0) {
                        setResult(1);
                        finish();
                        return;
                    }
                    tv_fabu.setEnabled(true);
                    ToastUtils.showToast(response.getErrMsg());
                }
                @Override
                protected void onError(Throwable throwable) {
                    super.onError(throwable);
                    tv_fabu.setEnabled(true);
                    ToastUtils.showToast("发布失败,请稍后重试");
                }
            });
        }else {
            tv_fabu.setEnabled(true);
        }


    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 2) {
            if (data != null) {
                upbitmap = null;
                if (data.getExtras() != null && !("").equals(data.getExtras())) {
                    upbitmap = (Bitmap) data.getExtras().get("data");
                } else {
                    String str = data.getDataString();
                    if (str == null) {
                        return;
                    }
                    Uri uri = Uri.parse(str);
                    String path = GetAbserlutePath.getPath(this, uri);
                    if (path.endsWith("png") || path.endsWith("jpg") || path.endsWith("jpeg")) {// 图片
                        upbitmap = ImageLoader.getInstance().loadImageSync("file://" + path);
                    } else {
                        ToastUtils.showToast("请选择.jpg或.png格式的图片!");
                        return;
                    }
                }
                upbitmap = getSmallBitmap(upbitmap);
                file = bitmapToString(upbitmap);
                title_img.setImageBitmap(upbitmap);
            }
        } else {
            getPhotoOrImage.onActivityResult(requestCode, resultCode, data);
        }
    }

    // 把bitmap转换成String
    public static String bitmapToString(Bitmap bgimage) {
        Bitmap bm = getSmallBitmap(bgimage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bm.compress(Bitmap.CompressFormat.JPEG, 40, baos);
        byte[] b = baos.toByteArray();
        return Base64.encodeToString(b, Base64.DEFAULT);
    }

    // 根据路径获得图片并压缩，返回bitmap用于显示
    public static Bitmap getSmallBitmap(Bitmap bgimage) {
        final BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;

        // Calculate inSampleSize
        options.inSampleSize = calculateInSampleSize(options, 480, 800);

        // Decode bitmap with inSampleSize set
        options.inJustDecodeBounds = false;

        // return BitmapFactory.decodeFile(filePath, options);
        return ZoomBitmap.zoomImage(bgimage, bgimage.getWidth()
                / options.inSampleSize, bgimage.getHeight() / options.inSampleSize);
    }

    // 计算图片的缩放值
    public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }
}
